﻿using System;
using System.IO;
using System.Text;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// 在Strem中读取或写入指定字节长度的字符串
    /// </summary>
    public class StreamString
    {
        private readonly Encoding _encoding;

        /// <summary>
        /// 构造函数初始化
        /// </summary>
        /// <param name="encoding">字符串默认编码</param>
        /// <exception cref="ArgumentNullException">字符串默认编码为null异常</exception>
        public StreamString(Encoding encoding)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            this._encoding = encoding;
        }



        /// <summary>
        /// 写指定字节长度的字符串
        /// </summary>
        /// <param name="writer">BinaryWriter</param>
        /// <param name="str">要写入的字符串</param>
        /// <param name="length">写入字节数</param>
        public void WriteFixByteLengthString(BinaryWriter writer, string str, int length)
        {
            StreamEx.WriteFixByteLengthString(writer, str, length, this._encoding);
        }

        /// <summary>
        /// 读取指定字节长度的字符串
        /// </summary>
        /// <param name="reader">BinaryReader</param>
        /// <param name="length">读取字节数</param>
        /// <returns>读取到的字符串</returns>
        public string ReadFixByteLengthString(BinaryReader reader, int length)
        {
            return StreamEx.ReadFixByteLengthString(reader, length, this._encoding);
        }

    }

}
